/**
 * @Title: ExampleFile.java
 * @Package com.example.package
 * @Description: Placeholder (briefly describe the purpose of this file)
 * @Author: Evan
 * @Date: 2023-08-18
 * @Version: V1.0
 *
 * Copyright Notice:
 * This project is released in open source and follows the applicable open source license.
 * All rights reserved. (c) 2023 Evan.
 * This project is protected by copyright laws and international copyright treaties.
 * Unauthorized reproduction, sale, copy, modification, merge, publication, distribution,
 * licensing, and/or sales of this software and its copies are prohibited without permission.
 * Please contact the author for authorization.
 * Contact Information:
 * @Email: uyevan@163.com
 */

package com.evan.biznak.vip.Activity;

import static com.evan.biznak.vip.Config.Config.API_URL;
import static com.evan.biznak.vip.Config.Config.APP_ID;
import static com.evan.biznak.vip.Config.Config.KEEPER;
import static com.evan.biznak.vip.Util.FileUtil.evanVip;
import static com.evan.biznak.vip.Util.ShaUtil.isOrgApp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AlertDialog;

import com.evan.biznak.vip.Class.AppData;
import com.evan.biznak.vip.R;
import com.evan.biznak.vip.Util.AES;
import com.evan.biznak.vip.Util.SharePreferencesUtils;
import com.evan.biznak.vip.Util.WindowUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import es.dmoral.toasty.Toasty;

@SuppressLint("HardwareIds")
public class MainActivity extends Activity {

    /*私有变量*/
    private static final int DELAY_TIME = 1500;
    private KProgressHUD kProgressHUD;
    private Context context;
    private AlertDialog dialog;

    /*卡密验证*/
    private boolean Key_Start;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = MainActivity.this;
        /*签名校验*/
        Context context = getApplicationContext();
        boolean is_org_app = false;
        try {
            is_org_app = isOrgApp(context);
        } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (!is_org_app) {
            /*如果签名不一致，说明程序被修改了，直接退出*/
            Process.killProcess((Process.myPid()));
        }
        setContentView(R.layout.activity_main);
        /* 权限获取 */
        /*XXPermissions.with(this)
                // PHONE
                .permission(Permission.READ_PHONE_NUMBERS)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Toasty.info(MainActivity.this, "部分权限未正常授予", Toasty.LENGTH_LONG, true).show();
                            return;
                        }
                        agreement();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Toasty.error(MainActivity.this, "无法获取电话权限，请授权后重试", Toasty.LENGTH_LONG, true).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(context, permissions);
                        } else {
                            Toasty.error(MainActivity.this, "授权电话权限失败", Toasty.LENGTH_LONG, true).show();
                        }
                    }
                });*/
        /*协议*/
        agreement();
        /*Dialog*/
        kProgressHUD = KProgressHUD.create(MainActivity.this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setLabel("Biznak加载中").setCancellable(false).setAnimationSpeed(2).setDimAmount(0.5f);
        /*Log.e("AndroidID", getDeviceId());*/
    }


    /*协议验证*/
    @SuppressLint("MissingPermission")
    private void agreement() {
        if (!SharePreferencesUtils.checkString(MainActivity.this, "agreement")) {
            dialog = new MaterialAlertDialogBuilder(MainActivity.this).setPositiveButton(R.string.我同意, null).setNegativeButton(R.string.我拒绝, null).setCancelable(false).setTitle(R.string.biznak服务协议).setMessage(getString(R.string.agree)).create();
            dialog.setOnShowListener(dialogs -> {
                Button N_button = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                Button P_button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                /*接受*/
                P_button.setOnClickListener(v -> {
                    Toasty.success(MainActivity.this, "你已接受协议", Toasty.LENGTH_LONG, true).show();
                    SharePreferencesUtils.saveString(MainActivity.this, "agreement", "true");
                    dialog.dismiss();
                    newApp();
                });
                /*拒绝*/
                N_button.setOnClickListener(v -> {
                    Toasty.error(MainActivity.this, "你拒绝协议", Toasty.LENGTH_LONG, true).show();
                    dialog.dismiss();
                    finish();
                });
            });
            dialog.show();
            return;
        }
        newApp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在 Activity onDestroy() 方法中关闭对话框
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /*获取设备信息*/
    // 账户
    private String getDeviceId() {
        return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID).replaceAll("\\D+", ""); //AndroidID
    }

    // 密码
    private String getIccId() {
        return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID).replaceAll("\\D+", ""); //AndroidIDv
    }

    /*登录或注册*/
    private void Login() {
        kProgressHUD.show();
        HttpParams params = new HttpParams();
        params.put("keeper", evanVip(KEEPER, context));
        params.put("api", evanVip(APP_ID, context));
        params.put("user", getDeviceId());
        params.put("pass", getIccId());
        if (WindowUtils.checkNetworkStatus(MainActivity.this)) {
            EasyHttp.get(evanVip(API_URL, context).concat("uyyun_login.php")).params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    finish();
                }

                @Override
                public void onSuccess(String data) {
                    String s = AES.decrypt(data, context);
                    // Log.e("s", s);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        if (jsonObject.getString("code").equals("true")) {
                            /* 存储签名 */
                            AppData.setSignName(jsonObject.getString("signtext"));
                            kProgressHUD.dismiss();
                            /*账户存在并且登录成功  -》 进行会员验证*/
                            if (jsonObject.getString("vip").equals("true")) {
                                /*是会员进入软件*/
                                toStartActivity();
                            } else {
                                /*进行卡密验证*/
                                @SuppressLint("InflateParams") View dia_key_view = getLayoutInflater().inflate(R.layout.dia_key_view, null);
                                TextInputLayout key_layout = dia_key_view.findViewById(R.id.key_layout);
                                TextInputEditText key = dia_key_view.findViewById(R.id.key);
                                final AlertDialog alertDialog = new MaterialAlertDialogBuilder(MainActivity.this).setIcon(R.drawable.twotone_cruelty_free_24).setPositiveButton(R.string.解锁, null).setNegativeButton(R.string.获取解锁码, null).create();
                                alertDialog.setTitle(getString(R.string.设备解锁));
                                alertDialog.setMessage(getString(R.string.biznak_qq_341368849));
                                alertDialog.setView(dia_key_view);
                                alertDialog.setCancelable(false);
                                alertDialog.setOnShowListener(dialog -> {
                                    Button button_negative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                                    button_negative.setOnClickListener(v -> {
                                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + "3487297072" + "&version=1")));

                                    });
                                    Button button_positive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                                    button_positive.setOnClickListener(v -> {
                                        /*空验证*/
                                        String key_data = Objects.requireNonNull(key.getText()).toString().trim();
                                        if (key_data.equals("")) {
                                            key_layout.setError("请输入解锁码");
                                            return;
                                        }
                                        key_layout.setError(null);
                                        if (key_data.length() != 18) {
                                            key_layout.setError("请输入正确的解锁码");
                                            return;
                                        }
                                        key_layout.setError(null);
                                        HttpParams params1 = new HttpParams();
                                        params1.put("keeper", evanVip(KEEPER, context));
                                        params1.put("api", evanVip(APP_ID, context));
                                        params1.put("user", getDeviceId());
                                        params1.put("pass", getIccId());
                                        params1.put("key", key_data);
                                        if (WindowUtils.checkNetworkStatus(MainActivity.this)) {
                                            EasyHttp.get(evanVip(API_URL, context).concat("cdkey_user_use.php")).params(params1).execute(new SimpleCallBack<String>() {
                                                @Override
                                                public void onError(ApiException e) {
                                                    finish();
                                                }

                                                @Override
                                                public void onSuccess(String data1) {
                                                    String s1 = AES.decrypt(data1, context);
                                                    try {
                                                        JSONObject jsonObject1 = new JSONObject(s1);
                                                        if (jsonObject1.getString("code").equals("true")) {
                                                            /*总换成功*/
                                                            Login();
                                                            alertDialog.dismiss();
                                                        } else {
                                                            Toasty.error(MainActivity.this, jsonObject1.getString("msg"), Toasty.LENGTH_SHORT, true).show();
                                                            key_layout.setError(jsonObject1.getString("msg"));
                                                        }
                                                    } catch (JSONException e) {
                                                        throw new RuntimeException(e);
                                                    }
                                                }
                                            });
                                        }
                                    });
                                });
                                alertDialog.show();
                            }
                        } else {
                            if (jsonObject.getString("msg").contains("账号不存在")) {
                                /*进行注册*/
                                Register();
                            } else {
                                Toasty.error(MainActivity.this, jsonObject.getString("msg"), Toasty.LENGTH_SHORT, true).show();
                                finish();
                            }
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    } finally {
                        kProgressHUD.dismiss();
                    }
                }
            });
        }
    }

    /*注册*/
    private void Register() {
        HttpParams params = new HttpParams();
        params.put("keeper", evanVip(KEEPER, context));
        params.put("api", evanVip(APP_ID, context));
        params.put("user", getDeviceId());
        params.put("pass", getIccId());
        params.put("name", "Biznak");
        if (WindowUtils.checkNetworkStatus(MainActivity.this)) {
            EasyHttp.get(evanVip(API_URL, context).concat("uyyun_userreg.php")).params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    finish();
                }

                @Override
                public void onSuccess(String data) {
                    String s = AES.decrypt(data, context);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        if (jsonObject.getString("code").equals("true")) {
                            /*账户注册成功  -》 进行登录*/
                            Login();
                        } else {
                            Toasty.error(MainActivity.this, jsonObject.getString("msg"), Toasty.LENGTH_SHORT, true).show();
                            finish();
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    } finally {
                        kProgressHUD.dismiss();
                    }
                }
            });
        }
    }


    /*获取版本*/
    private String getVersion() {
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /*版本更新*/
    private void newApp() {
        new Thread(() -> {
            try {
                if (WindowUtils.checkNetworkStatus(MainActivity.this)) {
                    EasyHttp.get("https://gitee.com/uyevan/UY-Cloud/raw/main/biznak").headers("Charset", "UTF-8").execute(new SimpleCallBack<String>() {
                        @Override
                        public void onError(ApiException e) {
                            if (!joinQQGroup("Q5ho2_DnJR60dxwgjIjgXokBdGlFPo72")) {
                                Toasty.info(MainActivity.this, "请安装QQ并重启应用", Toasty.LENGTH_SHORT, true).show();
                            }
                        }

                        @Override
                        public void onSuccess(String data) {
                            /* 加密处理 */
                            String s = AES.decrypt(data, context);
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                Key_Start = jsonObject.getBoolean("Key_Start");
                                AppData.setWxQr(jsonObject.getString("wx_qr"));
                                AppData.setZfbQr(jsonObject.getString("zfb_qr"));
                                AppData.setSPONSOR(jsonObject.getBoolean("sponsor"));
                                AppData.setQqKey(jsonObject.getString("qq_key"));
                                if (!jsonObject.getString("version").equals(getVersion())) {
                                    /*有新版本*/
                                    AlertDialog alertDialog = new MaterialAlertDialogBuilder(MainActivity.this).setIcon(R.drawable.twotone_cruelty_free_24).setNegativeButton(R.string.立即更新, (dialog, which) -> {
                                        try {
                                            joinQQGroup(jsonObject.getString("qq_key"));
                                        } catch (JSONException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }).setTitle(R.string.biznak更新啦).setMessage(jsonObject.getString("content")).setCancelable(false).create();
                                    alertDialog.show();
                                } else {
                                    /*卡密验证*/
                                    if (jsonObject.getBoolean("Key_Start")) {
                                        // 验证
                                        Login();
                                        return;
                                    }
                                    /*无需验证*/
                                    toStartActivity();
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    /**
     * Join qq group boolean.
     *
     * @param key the key
     * @return the boolean
     */
    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    private void toStartActivity() {
        /*延迟跳转*/
        new Handler().postDelayed(() -> {
            Intent intent = new Intent(MainActivity.this, StartActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.nav_in_anim, R.anim.nav_en_anim);
            finish();
        }, DELAY_TIME);
    }

}